﻿'         This file is Copyright © 2008-2012 Billy O'Neal and Aommaster
'                            All rights reserved.
'
' This file is released under the 2-Clause BSD license, included in LICENSE.TXT
'                           and on the MHWT website
Imports System.ComponentModel
Imports System.Xml.Serialization
Imports System.IO

Friend Class SpeechDatabase
    WithEvents speechDatabase As BindingList(Of Speech) = GlobalData.canDatabase

    Public Sub populateSpeeches() Handles speechDatabase.ListChanged
        For Each item As Speech In speechBox.Items
            RemoveHandler item.Modified, AddressOf populateSpeeches
            RemoveHandler item.Deleted, AddressOf populateSpeeches
        Next
        speechBox.Items.Clear()
        For Each item As Speech In speechDatabase
            AddHandler item.Modified, AddressOf populateSpeeches
            AddHandler item.Deleted, AddressOf populateSpeeches
            speechBox.Items.Add(item)
        Next
    End Sub

    Private Sub btnAdd_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAdd.Click
        Dim editedCan As New Speech
        speechDatabase.Add(editedCan)
        Dim frm As New EditCan(editedCan)
        frm.MdiParent = Me.MdiParent
        frm.Show()
    End Sub

    Private Sub btnEdit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnEdit.Click
        If speechBox.SelectedItem Is Nothing Then
            MsgBox("You have to select something to edit first!")
        Else
            For Each selectedspeech As Speech In speechBox.SelectedItems
                Dim frm As New EditCan(CType(selectedspeech, Speech))
                frm.MdiParent = Me.MdiParent
                frm.Show()
            Next


        End If
    End Sub

    Private Sub btnDelete_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnDelete.Click
        If speechBox.SelectedItem Is Nothing Then
            MsgBox("You have to select something to delete first!")
        Else
            Dim selected As System.Windows.Forms.ListBox.SelectedIndexCollection = speechBox.SelectedIndices()
            Dim selectedarray(selected.Count() - 1) As Integer
            For i = 0 To UBound(selectedarray)
                selectedarray(i) = selected(i) - i
            Next

            For i = 0 To UBound(selectedarray)
                speechBox.SelectedIndex = selectedarray(i)
                Dim can As Speech = DirectCast(speechBox.SelectedItem, Speech)
                can.delete()
                speechDatabase.Remove(can)

            Next

        End If
    End Sub
    Private Sub speechDatabase_FormClosed(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosedEventArgs) Handles Me.FormClosed
        For Each item As Speech In speechBox.Items
            RemoveHandler item.Modified, AddressOf populateSpeeches
            RemoveHandler item.Deleted, AddressOf populateSpeeches
        Next
        speechBox.Items.Clear()

        My.Computer.Registry.CurrentUser.CreateSubKey("SOFTWARE\BillyOneal\MHWT")
        Dim regKey As Microsoft.Win32.RegistryKey = My.Computer.Registry.CurrentUser.OpenSubKey("SOFTWARE\BillyOneal\MHWT", True)
        Try
            If Me.WindowState = FormWindowState.Maximized Then
                regKey.SetValue("SpeechMaximized", True)
            Else
                regKey.SetValue("SpeechMaximized", False)
            End If
            regKey.SetValue("SpeechW", CInt(Me.Bounds.Width))
            regKey.SetValue("SpeechH", CInt(Me.Bounds.Height))
        Catch ex As Exception
            MsgBox("Failed to save window state.")
        End Try
        regKey.Close()

        Dim fs As New IO.FileStream(System.IO.Path.Combine(Application.StartupPath, "Data.db"), IO.FileMode.Create)
        Dim formatter As New System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
        Dim temp As New DataFrontend
        formatter.Serialize(fs, temp)
        fs.Close()
    End Sub

    Private Sub speechDatabase_Shown(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Shown

        Try
            Dim regKey As Microsoft.Win32.RegistryKey = My.Computer.Registry.CurrentUser.OpenSubKey("SOFTWARE\BillyOneal\MHWT\", False)
            Dim max As Boolean = CBool(regKey.GetValue("SpeechMaximized"))
            Dim width As Int32 = CInt(regKey.GetValue("SpeechW"))
            Dim height As Int32 = CInt(regKey.GetValue("SpeechH"))
            If max Then
                Me.WindowState = FormWindowState.Maximized
            Else
                Me.SetBounds(0, 0, width, height)
            End If
        Catch ex As Exception
            Me.SetBounds(0, 0, 488, 250)
        End Try

        populateSpeeches()

    End Sub

    Private Sub speechBox_DoubleClick(ByVal sender As Object, ByVal e As System.EventArgs) Handles speechBox.DoubleClick
        If speechBox.SelectedItem IsNot Nothing Then
            Dim frm As New EditCan(CType(speechBox.SelectedItem, Speech))
            frm.MdiParent = Me.MdiParent
            frm.Show()
        End If
    End Sub
    Private Sub expSpeech_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles expSpeech.Click
        If speechBox.SelectedItem Is Nothing Then
            MsgBox("You have to select something to export first!")
        Else
            If speechBox.SelectedItems.Count = 1 Then
                Dim can As Speech = DirectCast(speechBox.SelectedItem, Speech)
                can.save()
            Else
                Dim dlg As New SaveFileDialog
                Dim tempfiles As New List(Of String)
                dlg.Filter = "Canned Speeches (*.cans)|*.cans"
                If dlg.ShowDialog() = DialogResult.OK Then
                    Dim i As Integer = 0
                    For Each cantosave As Speech In speechBox.SelectedItems
                        cantosave.save(Path.GetDirectoryName(dlg.FileName) + "\" + i.ToString + " - " + Path.GetFileName(dlg.FileName))
                        tempfiles.Add(Path.GetDirectoryName(dlg.FileName) + "\" + i.ToString + " - " + Path.GetFileName(dlg.FileName))
                        i += 1
                    Next

                    Dim tempstring As String = ""

                    Dim tempcan As StreamReader = Nothing

                    For Each tempfile As String In tempfiles
                        tempcan = New StreamReader(tempfile)
                        tempstring += tempcan.ReadToEnd + "-This is the end of the canned speech-"
                        tempcan.Close()
                        File.Delete(tempfile)
                    Next
                    tempstring = tempstring.Substring(0, tempstring.Length - 38)

                    Dim finalcan2 As New IO.FileStream(dlg.FileName, IO.FileMode.Create)
                    finalcan2.Close()
                    Dim finalcan As New System.IO.StreamWriter(dlg.FileName)
                    finalcan.Write(tempstring)
                    finalcan.Close()
                End If
            End If
        End If
    End Sub

    Private Sub impSpeech_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles impSpeech.Click
        Dim dlg As New OpenFileDialog
        dlg.Filter = "Canned Speeches (*.can)|*.can|Canned Speeches Group (*.cans)|*.cans|XML Files (*.xml)|*.xml|Text Files (*.txt)|*.txt"
        If dlg.ShowDialog() = DialogResult.OK Then
            If Path.GetExtension(dlg.FileName) = ".cans" Then
                Dim tempreader As New StreamReader(dlg.FileName)
                Dim tempstring As String = tempreader.ReadToEnd()

                Dim filecontents() = tempstring.Split(New String() {"-This is the end of the canned speech-"}, StringSplitOptions.RemoveEmptyEntries)

                For i = 0 To UBound(filecontents)
                    Dim finalcan2 As New IO.FileStream(Path.GetDirectoryName(dlg.FileName) + "\" + i.ToString + " - " + Path.GetFileNameWithoutExtension(dlg.FileName) + ".can", IO.FileMode.Create)
                    finalcan2.Close()
                    Dim finalcan As New System.IO.StreamWriter(Path.GetDirectoryName(dlg.FileName) + "\" + i.ToString + " - " + Path.GetFileNameWithoutExtension(dlg.FileName) + ".can")
                    finalcan.Write(filecontents(i))
                    finalcan.Close()
                    Dim loadedCan As New Speech
                    loadedCan.load(Path.GetDirectoryName(dlg.FileName) + "\" + i.ToString + " - " + Path.GetFileNameWithoutExtension(dlg.FileName) + ".can")
                    speechDatabase.Add(loadedCan)
                    File.Delete(Path.GetDirectoryName(dlg.FileName) + "\" + i.ToString + " - " + Path.GetFileNameWithoutExtension(dlg.FileName) + ".can")
                Next
            Else
                Dim loadedCan As New Speech
                loadedCan.load(dlg.FileName)
                speechDatabase.Add(loadedCan)
            End If
        End If

        'Dim loadedCan As New speech
        'loadedCan.load()
        'speechDatabase.Add(loadedCan)
    End Sub
End Class